const baseURL = 'https://travel.peibanmao.com';
//const baseURL = 'http://192.168.0.9:8089'
//const baseURL = 'https://236743xh37.oicp.vip'

function getToken() {
  return wx.getStorageSync('user_token') || null;
}

function getRefreshToken() {
  return wx.getStorageSync('user_refreshToken') || null;
}

function setToken(token) {
  wx.setStorageSync('user_token', token);
}

function setRefreshToken(refreshToken) {
  wx.setStorageSync('user_refreshToken', refreshToken);
}

function refreshToken() {
  const refreshToken = getRefreshToken();
  const defaultHeader = {
    'content-type': 'application/json',
  };
  let header = {
    ...defaultHeader
  };
  if (refreshToken) {
    header['Authorization'] = `Bearer ${refreshToken}`;
  }

  return new Promise((resolve, reject) => {
    // 发送请求到服务器以获取新的token  
    wx.request({
      url: baseURL + '/api/travelGraphy/auth/wxRefreshToken',
      method: 'GET',
      header: header,
      // 其他参数...  
      success: (res) => {
        console.log(res, 'reshhh')
        if (res.data && res.data.code === 200) {
          resolve(res.data.accessToken);
        } else if (res.data && res.data.code === 1511) {
          setToken(null)
          setRefreshToken(null)
        }
      },
      fail: (err) => {
        reject('请求失败: ' + err.message);
      }
    });
  });
}

// 封装请求函数  
function request(options) {
  const token = getToken();
  const defaultHeader = {
    'content-type': 'application/json',
  };

  let header = {
    ...defaultHeader
  };
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }

  // 如果 options 中有 header，则合并它们  
  if (options.header) {
    header = {
      ...header,
      ...options.header
    };
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: baseURL + options.url,
      data: options.data,
      header: header,
      method: options.method,
      timeout: 5000,
      success: (res) => {
        console.log(res, 'dldldl')
        if (res.data && res.data.code === 200) {
          resolve(res.data);
        } else if (res.data.code === 1501) {
          // 用 refreshToken()去刷新accessToken
          refreshToken().then(newToken => {
            setToken(newToken);
          }).catch(reject);
        } else {
          reject(res.data.msg || '请求错误');
        }
      },
      fail: (err) => {
        reject(err.message || '请求失败');
      }
    });
  });
}

// 导出请求函数  
export default request;